var app = getApp();
import request from '../../utils/request'
Page({
  data: {
    loading: true,
    cartList: [],
    totalNumber: 0,
    totalPrice: 0,
    checkedStatus: true,
    buyNumber: 0,
    buyPrice: 0,
    userId: 10
  },
  onLoad(){
     const that = this
     let userData = wx.getStorageSync('userInfo')
     if(!userData){
       this.setData({
         loading: true
       })
       wx.showToast({
         title: '前先登录',
         icon: 'error'
       })
     }
     let userInfo = JSON.parse(userData)
     this.setData({
       userId: userInfo.userId
     })
     this.getCarts();
     setTimeout(that.addCart,1000)
    },
  addCart(){
    const that = this
    let orderData = wx.getStorageSync('orderItem');
    if(orderData == '' || orderData == null) return;
    wx.removeStorage({
      key: 'orderItem'
    })
    let myData = JSON.parse(orderData);
    if(this.data.cartList.length == 0){
      console.log("hello")
      wx.request({
        url: 'http://localhost:8000/cart/add',
        data:{
          userId : this.data.userId,
          bookingTime: myData.time,
          proId: myData.proId,
          proNum: myData.prodCount
        },
        method: "GET"
      })
    }
    that.data.cartList.forEach(item=>{
      if(item.goodsId == myData.proId){
        item.time = myData.time
        item.goodsNum = item.goodsNum  + myData.prodCount
        wx.request({
          url: 'http://localhost:8000/cart/update',
          data: item,
          method: "POST"
        })
      }else{
        wx.request({
          url: 'http://localhost:8000/cart/add',
          data:{
            userId : this.data.userId,
            bookingTime: myData.time,
            proId: myData.proId,
            proNum: myData.prodCount
          },
          method: "GET"
        })
      }
    })
  },
  onShow() {
  },

  async getCarts(){
    let userId = this.data.userId
    var totalNumber = 0;
    var totalPrice = 0;
    var buyNumber = 0;
    var buyPrice = 0;
    const that = this
    let cartData = await request('/cart/get',{userId: userId})
    cartData.data.forEach(item =>{
      // 保留两位小数点
      const hours = new Date(Date.parse(item.bookingTime)).getHours() > 10 ? new Date(Date.parse(item.bookingTime)).getHours() : '0' + new Date(Date.parse(item.bookingTime)).getHours()
      const minutes = new Date(Date.parse(item.bookingTime)).getMinutes() > 10 ? new Date(Date.parse(item.bookingTime)).getMinutes() : '0' + new Date(Date.parse(item.bookingTime)).getMinutes();
      item.myTime = hours + ":" + minutes
      item.realPrice = item.realPrice.toFixed(2);
      item.marketPrice = item.marketPrice.toFixed(2);
      if (!item.status) {
        that.setData({ checkedStatus: false });
      } else {
        buyNumber += item.goodsNum;
        buyPrice += item.goodsNum * item.realPrice;
      }
      totalNumber += item.goodsNum;
      totalPrice += item.goodsNum * item.realPrice;
      if (item.goodsNum == item.stockNum) {
        item.plus_class = "disabled";
      } else {
        item.plus_class = "";
      }
      if (item.goodsNum == 1) {
        item.decr_class = "disabled";
      } else {
        item.decr_class = "";
      }
    })
    that.setData({
      cartList: cartData.data,
      loading: false,
      totalNumber: totalNumber,
      totalPrice: totalPrice.toFixed(2),
      buyNumber: buyNumber,
      buyPrice: buyPrice.toFixed(2)
    })
  
  },
  // 选择商品
  selectProduct(event) {
    var cartId = event.currentTarget.dataset.id;
    var checkedStatus = event.currentTarget.dataset.checkedStatus;
    var totalNumber = 0;
    var totalPrice = 0;
    var buyNumber = 0;
    var buyPrice = 0;
    var id = [];
    checkedStatus = checkedStatus === true;
    var changeStatus = true;
    this.data.cartList.forEach(item => {
      if (item.id == cartId || cartId == 0) {
        if (item.status != !checkedStatus) {
          id.push(item.id);
        }
        item.status = cartId == 0 ? !checkedStatus : !item.status;
      }
      if (!item.status) {
        changeStatus = false;
      } else {
        buyNumber += item.goodsNum;
        buyPrice += item.goodsNum * item.realPrice;
      }
      
      totalNumber += item.goodsNum;
      totalPrice += item.goodsNum * item.realPrice;
      wx.request({
        url: 'http://localhost:8000/cart/update',
        data: item,
        method: "POST"
      })
    });
    changeStatus = cartId == 0 ? !checkedStatus : changeStatus;
    this.setData({
      cartList: this.data.cartList,
      checkedStatus: changeStatus,
      totalNumber: totalNumber,
      totalPrice: totalPrice.toFixed(2),
      buyNumber: buyNumber,
      buyPrice: buyPrice.toFixed(2)
    });
  },
  // 改变商品数量
  changeNumber(event) {
    var cartId = event.currentTarget.dataset.id;
    var optType = event.currentTarget.dataset.type;
    var totalNumber = 0;
    var totalPrice = 0;
    var buyNumber = 0;
    var buyPrice = 0;
    this.data.cartList.forEach(item => {
      if (item.id == cartId) {
        if (optType == 'plus') {
          if (item.stockNum == item.goodsNum) {
            this.setData({
              toast: {
                toastClass: 'yatoast',
                toastMessage: '该宝贝不能购买更多哦'
              }
            });
            setTimeout(() => {
              this.setData({
                toast: {
                  toastClass: '',
                  toastMessage: ''
                }
              });
            }, 2000);
          } else {
            item.goodsNum++;
            this.updateCart(item);
          }

        } else {

          if (item.goodsNum <= 1) {
            this.setData({
              toast: {
                toastClass: 'yatoast',
                toastMessage: '亲，不能再减少了哦'
              }
            });
            setTimeout(() => {
              this.setData({
                toast: {
                  toastClass: '',
                  toastMessage: ''
                }
              });
            }, 2000);
          } else {
            item.goodsNum--;
            this.updateCart(item);
          }
        }
        if (item.goodsNum == item.stockNum) {
          item.plus_class = "disabled";
        } else {
          item.plus_class = "";
        }
        if (item.goods_number == 1) {
          item.decr_class = "disabled";
        } else {
          item.decr_class = "";
        }
      }
      if (!item.status) {

      } else {
        buyNumber += item.goodsNum;
        buyPrice += item.goodsNum * item.realPrice;
      }
      totalNumber += item.goodsNum;
      totalPrice += item.goodsNum * item.realPrice;
    });
    this.setData({
      cartList: this.data.cartList,
      totalNumber: totalNumber,
      totalPrice: totalPrice.toFixed(2),
      buyNumber: buyNumber,
      buyPrice: buyPrice.toFixed(2)
    });
  },
  updateCart(cartInfo){
    wx.request({
      url: 'http://localhost:8000/cart/update',
      data: cartInfo,
      method: "POST",
      header: {
         cookie: '',
         "Content-Type":"application/json"
      }
    })
  },
  // 去结算页面
  toSettlement() {
    if(this.data.buyNumber == 0) {
       this.showTips(this, '你还未勾选商品'); return;
    }
    let cartIds = []
    this.data.cartList.forEach(item =>{
      cartIds.push(item.id)
    })
    wx.setStorageSync('cartIds',cartIds)
    wx.navigateTo({
      url: '/pages/settlement/settlement',
    });
  },
  showTips(event, msg) {
    event.setData({
     toast: {
       toastClass: 'yatoast',
       toastMessage: msg
     }
   });
   setTimeout(() => {
     event.setData({
       toast: {
         toastClass: '',
         toastMessage: ''
       }
     });
   }, 2000);
 },
  // 去除购物车物品
 delProduct(event) {
    wx.showModal({
      content: '你确定在购物车中删除该商品',
      showCancel: true,
      success: (res) => {
        if(res.confirm == 0) {
          return;
        }
        var id = event.currentTarget.dataset.id;
        var cartList = this.data.cartList;
        var totalNumber = 0;
        var totalPrice = 0;
        var buyNumber = 0;
        var buyPrice = 0;
        var delKey = 0;
        cartList.forEach((item, key) => {
          if (item.id == id) {
            delKey = key;
          } else {
            if (!item.status) {

            } else {
              buyNumber += item.goodsNum;
              buyPrice += item.goodsNum * item.realPrice;
            }
            totalNumber += item.goodsNum;
            totalPrice += item.goodsNum * item.realPrice;
          }
        });
        cartList.splice(delKey, 1);
        wx.request({
          url: 'http://localhost:8000/cart/delete?id='+id,
          method:"DELETE",
          success(res){
            wx.showToast({
              title: '删除成功',
            })
          },
          fail(){
            wx.showToast({
              title: '删除失败',
            })
          }
        })
        this.setData({
          cartList: cartList,
          totalNumber: totalNumber,
          totalPrice: totalPrice.toFixed(2),
          buyNumber: buyNumber,
          buyPrice: buyPrice.toFixed(2)
        })
      }
    });
   
  },
  navigateTo() {
    wx.switchTab({
      url: '/pages/index/index'
    });
  }
});
